package com.saxon.system.ajax;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ajax验证失败处理类
 *
 * @author saxon
 */
@Component
public class AjaxAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
    /**
     * 请求失败处理方法
     *
     * @param request   请求
     * @param response  响应
     * @param exception 如果登陆不成功返回的异常
     * @throws IOException      异常
     * @throws ServletException 异常
     */
    @Override
    public void onAuthenticationFailure (HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //处理ajax请求
        if (exception instanceof BadCredentialsException) {
            response.sendError (HttpServletResponse.SC_UNAUTHORIZED, "密码错误");
        } else if (exception instanceof LockedException) {
            response.sendError (HttpServletResponse.SC_BAD_REQUEST, "该用户已经被锁住");
        }
    }
}
